#ifndef __TCPCONNECTION_H__
#define __TCPCONNECTION_H__
#include "Socket.h"
#include "SocketIO.h"
#include "InetAddr.h"
#include "EventLoop.h"
#include <functional>

#include <memory>

using std::function;
using std::shared_ptr;

class SubReactor;

class TcpConnection
: public std::enable_shared_from_this<TcpConnection>
{
    using TcpConnectionPtr = shared_ptr<TcpConnection>;
    using TcpConnectionCallback = function<void(const TcpConnectionPtr &)>;
public:
    explicit TcpConnection(int fd, EventLoop* loop);
    explicit TcpConnection(int fd, SubReactor* reactor);
    ~TcpConnection();
    void send(const string &msg);
    string receive();
    string toString();
    InetAddr getLocalAddr();
    InetAddr getPeerAddr();
    bool isClose() const;
    void setNewConnectionCallback(const TcpConnectionCallback &cb);
    void setMessageCallback(const TcpConnectionCallback &cb);
    void setCloseCallback(const TcpConnectionCallback &cb);
    void handleNewConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();

    void sendInLoop(const string &msg);//执行send交给EventLoop
    int fd() const { return _sock.fd(); } // 获取socket文件描述符

private:
    SocketIO _sockIO;
    Socket _sock;
    InetAddr _lAddr;//本地ip
    InetAddr _pAddr;//对端ip
                    
    TcpConnectionCallback _onNewConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;

    EventLoop *_loop;
    SubReactor *_reactor;

};


#endif

